using System;
using System.Collections.Generic;
using System.Text;
using FriendsNearby.Services.Entities;
using Facebook.Service.Core;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;

namespace FriendsNearby.Services
{
    public class UsersService : IUsersService
    {
        DataAccess da;
        IServiceProvider serviceProvider;

        public UsersService(IServiceProvider serviceProvider)
        {
            da = PolicyInjection.Create<DataAccess>();
            this.serviceProvider = serviceProvider;
        }


        ILocationService LocationService
        {
            get { return serviceProvider.GetService<ILocationService>(); }
        }

        #region IUsersService Members

        public void RegisterFacebookUser(string userId, string sessionKey)
        {
            // store session Key
            da.AddUserRegistry(userId, sessionKey);
            
            // default preferences
            UserPreference defaultPreferences = new UserPreference();
            defaultPreferences.FacebookUserId = userId;
            defaultPreferences.VisibilityLevel = (int)VisibilityLevel.FriendsAndTheirFriends;
            defaultPreferences.NearbyRadiusKM = 50;
            SetUserPreferences(defaultPreferences);

            // initialize location store for user
            LocationService.InitializeLocation(userId);
        }

        public void EnsureUserRegistryExists(string userID, string sessionKey)
        {
            da.EnsureUserExists(userID, sessionKey);
        }

        public void UnregisterFacebookUser(string userId)
        {
            da.RemoveUserPreferences(userId);
            LocationService.RemoveLocation(userId);
            da.RemoveUserRegistry(userId);
        }

        public UserPreference GetUserPreferences(string userId)
        {
            UserPreference p = da.ReadUserPreferences(userId);
            if (p == null)
            {
                p = new UserPreference();
                p.FacebookUserId = userId;
                p.NearbyRadiusKM = 100;
                p.VisibilityLevel = (int)VisibilityLevel.Nobody;
            }
            return p;
        }

        public void SetUserPreferences(UserPreference preferences)
        {
            da.UpdateUserPreferences(preferences);
        }

		public string GetFacebookUserIdFromTwitter(string screenName)
		{
			return da.GetFacebookUserIdFromTwitter(screenName);
		}

        public string GetInternalUserIDFromFacebookUserID(string facebookUserID)
        {
            return da.GetInternalUserIDFromFacebookUserID(facebookUserID);
        }

        public string GetFacebookUserIDFromInternalUserID(string internalUserID)
        {
            return da.GetFacebookUserIDFromInternalUserID(internalUserID);
        }

        #endregion
    }
}
